<template>
  <div>
    <div class="uploadImages">
      <el-upload
        ref="upload"
        :action="url"
        :data="paramsData"
        list-type="picture-card"
        :name="paramsData.fileName"
        :auto-upload="false"
        :before-upload="beforeUploadHandle"
        :on-success="successHandle"
        :on-error="errorHandle"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
      </el-upload>

      <el-input
        type="textarea"
        :rows="2"
        placeholder="请输入内容"
        v-model="textarea">
      </el-input>
    </div>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import { getInterface } from '../../../utils/api'
  import { userInfoCookies } from '../../../storage'

  export default {
    name: 'uploadImage',
    props: ['paramsData'],
    data () {
      return {
        url: '',
        num: 0,
        successNum: 0,
        dialogImageUrl: '',
        dialogVisible: false,
        textarea: ''
      }
    },
    methods: {
      init () {
        this.url = getInterface.uploadImage + '?token=' + userInfoCookies.getToken()
      },
      submitUpload () {
        this.$refs.upload.submit()
      },
      // 上传之前
      beforeUploadHandle (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
        this.num++
      },
      // 上传成功
      successHandle (response, file, fileList) {
        this.successNum++
        if (response && response.code === 0) {
          this.$message({
            message: '图片上传成功',
            type: 'success'
          })
        } else {
          this.$refs.upload.clearFiles()
          this.$message.error(response.msg)
        }
      },
      errorHandle () {
        this.$refs.upload.clearFiles()
        this.$message.error('图片上传失败')
      },
      handleRemove (file, fileList) {
        //
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      }
    }
  }
</script>

<style scoped lang="scss">
.uploadImages{
  width: 300px;
  margin: 0 auto;

  .el-textarea{
    margin-top: 15px;
  }
}
</style>
